package cn.ainit.bj.flow;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.junit.Test;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.ainit.bj.flow.entity.FlowNode;
import cn.ainit.bj.flow.entity.ReturnNodeStore;
import cn.ainit.common.ReturnObject;
import cn.ainit.sys.ds.store.StoreController;
import cn.ainit.sys.ds.store.StoreService;
import cn.ainit.sys.menu.SessionCont;
import cn.ainit.sys.menu.SysFunctions;
import cn.ainit.sys.query.datastore.DataStore;
import cn.ainit.sys.query.entity.QueryJson;

@Controller
@RequestMapping("/bjFlow")
public class BjFlowController {
	
	private BjFlowService bjFlowService;
	@Resource
	public void setBjFlowService(BjFlowService bjFlowService) {
		this.bjFlowService = bjFlowService;
	}
	private StoreService storeService;

	@Resource
	public void setStoreService(StoreService storeService) {
		this.storeService = storeService;
	}
	
	
	/****
	 * 我的工作台双击调用参数
	 * @param flowId
	 * @param manageId
	 * @param session
	 * @param request
	 * @return
	 * @throws Exception
	 * @author feifei
	 * @date: 2015-5-14 下午02:23:01 
	 */
	@RequestMapping("/dsIdByNode")
	@ResponseBody
	public ReturnNodeStore getDsIdByNode(String flowId,String manageId,HttpSession session,HttpServletRequest request) throws Exception{
		ReturnNodeStore returnObject = new ReturnNodeStore();
		String uid = session.getAttribute(SessionCont.uid).toString();//当前登陆人id
		String flagStr = ""; //执行存储过程返回的标志位
		String flagNum = "";
		List<Map<String,Object>> listManage = new ArrayList<Map<String,Object>>();
		List<Map<String,Object>> listNode = new ArrayList<Map<String,Object>>();
		try {
			flagNum = this.bjFlowService.execProcForP(manageId);
			if (!"1".equals(flagNum)) {
				listManage = this.bjFlowService.getFlowManager(manageId);
				listNode = this.bjFlowService.getNodeById(listManage.get(0).get("PARENT_FLOW_ID").toString());
				String nodeName = listNode.get(0).get("FLOW_NAME").toString();
				returnObject.setInfo(nodeName);
				returnObject.setMsg("noPar");
			}else {
				//获取一个flowNode 节点
				FlowNode flowNode= this.bjFlowService.getDsIdForNode(flowId);
				if(flowNode==null||flowNode.getDsId()==null||"".equals(flowNode.getDsId())){
					System.out.println("#74  bjFlowController 获取flowNode 有问题，请马上检查错误代码");
				}
				returnObject.setDsId(flowNode.getDsId());
				SysFunctions funObj=this.bjFlowService.getSysFun(flowNode.getDsId());
				String winitFunc="";   //详情页面的回调函数
				String ainitFunc="";	//添加页面的回调函数
				//../singlePages/mqueryFun?dsId=ds_yz_print_explain1;ds_yz_print_explain_item1&type=4;3;6&staticWebUrl=&initFunc=&ainitFunc=quHideButnM&flag=1&winitFunc=bindExp
				if(funObj!=null){
					if(!"".equals(funObj.getUrl().trim())&&funObj.getUrl().lastIndexOf("winitFunc=")!=-1){
						String str=funObj.getUrl().substring(funObj.getUrl().lastIndexOf("winitFunc="));
						int strIndex=str.indexOf("&");
						if(strIndex==-1){
							winitFunc=str.substring("winitFunc=".length());
						}else{
							if((funObj.getUrl().indexOf("winitFunc=")+1)==strIndex){
								winitFunc="";
							}
							else{
								winitFunc=str.substring("winitFunc=".length(),strIndex);
							}
						}
					}
					
					if(funObj.getUrl()!=null&&!"".equals(funObj.getUrl().trim())&&funObj.getUrl().lastIndexOf("ainitFunc=")!=-1){
						String str=funObj.getUrl().substring(funObj.getUrl().indexOf("ainitFunc="));
						int strIndex=str.indexOf("&");
						if(strIndex==-1){
							ainitFunc=str.substring("ainitFunc=".length());
						}else{
							if((funObj.getUrl().indexOf("ainitFunc=")+1)==strIndex){
								ainitFunc="";
							}
							else{
								ainitFunc=str.substring("ainitFunc=".length(),strIndex);
							}
						}
					}
				}
				returnObject.setFuncId(flowNode.getFuncId());
				returnObject.setWinitFunc(winitFunc);
				returnObject.setAinitFunc(ainitFunc);
				String[] dsIds = flowNode.getDsId().split(";");
				DataStore dataStore = storeService.findStore(dsIds[0]);
				returnObject.setDataStore(dataStore);
				System.out.println(dataStore.getSmoro());
				flagStr = this.bjFlowService.execjudgenode(manageId,flowNode.getDsId(),uid); //执行存储过程
				returnObject.setMsg(flagStr);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return returnObject;
	}
	
	
	/*******
	 * 点击消息提示需要调用的参数
	 * @param dsid
	 * @param djid
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("returnData")
	@ResponseBody
	public ReturnNodeStore getData(String dsid,String djid) throws Exception{
		ReturnNodeStore returnObject=new ReturnNodeStore();
	   //获取主键id
		String msg =bjFlowService.getKey(dsid.split(";")[0]);
		returnObject.setPkName(msg);
		returnObject.setMsg(msg+"-"+djid);
		SysFunctions funObj=this.bjFlowService.getSysFun(dsid);
		String winitFunc="";   //详情页面的回调函数
		String ainitFunc="";	//添加页面的回调函数
		if(funObj!=null){
			if(!"".equals(funObj.getUrl().trim())&&funObj.getUrl().lastIndexOf("winitFunc=")!=-1){
				String str=funObj.getUrl().substring(funObj.getUrl().lastIndexOf("winitFunc="));
				int strIndex=str.indexOf("&");
				if(strIndex==-1){
					winitFunc=str.substring("winitFunc=".length());
				}else{
					if((funObj.getUrl().indexOf("winitFunc=")+1)==strIndex){
						winitFunc="";
					}
					else{
						winitFunc=str.substring("winitFunc=".length(),strIndex);
					}
				}
			}
			
			if(funObj.getUrl()!=null&&!"".equals(funObj.getUrl().trim())&&funObj.getUrl().lastIndexOf("ainitFunc=")!=-1){
				String str=funObj.getUrl().substring(funObj.getUrl().indexOf("ainitFunc="));
				int strIndex=str.indexOf("&");
				if(strIndex==-1){
					ainitFunc=str.substring("ainitFunc=".length());
				}else{
					if((funObj.getUrl().indexOf("ainitFunc=")+1)==strIndex){
						ainitFunc="";
					}
					else{
						ainitFunc=str.substring("ainitFunc=".length(),strIndex);
					}
				}
			}
		}
		returnObject.setDsId(funObj.getDsId());
		returnObject.setFuncId(funObj.getMenuid());
		returnObject.setWinitFunc(winitFunc);
		returnObject.setAinitFunc(ainitFunc);
		DataStore dataStore = storeService.findStore(dsid.split(";")[0]);
		returnObject.setDataStore(dataStore);
		return returnObject;
	}
	
	
	/***
	 * 上一条下一条 根据dsId到sys_function中找到详情界面的回调函数
	 * @param dsId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/getinitFuncByDsId")
	@ResponseBody
	public ReturnObject getinitFuncByDsId(String dsId) throws Exception{
		ReturnObject returnObject=new ReturnObject();
		SysFunctions funcObj=this.bjFlowService.getSysFun(dsId);
		String winitFunc="";
		if(funcObj!=null&&funcObj.getUrl()!=null&&!"".equals(funcObj.getUrl().trim())&&funcObj.getUrl().lastIndexOf("winitFunc=")!=-1){
			//../singlePages/mqueryFun?dsId=ds_yz_print_explain2;ds_yz_print_explain_item2&type=4;3&staticWebUrl=&initFunc=&ainitFunc=&flag=1&winitFunc=bindExp
			String str=funcObj.getUrl().substring(funcObj.getUrl().lastIndexOf("winitFunc="));
			String str1=str.substring(str.indexOf("=")+1);
			int strIndex=str1.indexOf("&");
			if(strIndex==-1){
				winitFunc=str1;
			}else{
				String str2=str1.substring(0,str1.indexOf("&"));
				winitFunc=str2;
			}
		}
		returnObject.setInfo(winitFunc);
		return returnObject;
	}
	
	
	/*******
	 * 
	 * 
	 * 点击超链接（数据挖掘）
	 * @param dsid
	 * @param djid
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("returnAHreData")
	@ResponseBody
	public ReturnNodeStore returnAHreData(String dsid,String realdsid,String djid,String colnName) throws Exception{
		ReturnNodeStore returnObject=this.getData(dsid, djid);
		String pkId=bjFlowService.getAHrefPkValue(realdsid, djid, colnName);
		if(pkId==null||pkId.equals("")){
			returnObject.setErrorMsg("no");
		}else{
			 if(pkId.indexOf("error:")!=-1){
				 returnObject.setErrorMsg(pkId);
			 }else{
				 returnObject.setPkId(pkId);
				 returnObject.setMsg(returnObject.getPkName()+"-"+pkId);
			 }
		}
		return returnObject;
	}
	
	/**
	 * 根据选题Id找到除去这个选题本身的flowManager
	 * @param xtId
	 * @param request
	 * @return
	 * @throws Exception
	 * @author wyang
	 * @date : 2014-6-16 下午08:07:20   
	 */
	@RequestMapping("/queryFlow")
	@ResponseBody
	public QueryJson queryFY(String xtId,String flowIds,HttpServletRequest request) throws Exception{
		QueryJson queryJson = new QueryJson();
		List list = new ArrayList();
		try {
			String sql ="";
			if(flowIds !=null && !"".equals(flowIds)){
				sql ="select * from bs_flownode f where not exists(select 1 from bs_flowmanager m where m.xt_id='"+xtId+"' and m.flow_id=f.flow_id)" +
				" and f.flow_id not in ("+flowIds+") ";
			}else {
				sql ="select * from bs_flownode f where not exists(select 1 from bs_flowmanager m where m.xt_id='"+xtId+"' and m.flow_id=f.flow_id)";
			}
			//执行sql 返回list<Object>
			list = this.bjFlowService.execSql(sql);
			queryJson.setRows(list);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return queryJson;
	}
	

}
